<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-input
          style="width: 300px"
          placeholder="请输入搜索关键字"
          size="small"
          class="m-r-10"
          clearable=""
          v-model="search.keyWord"
          @change="query"
        />
      </el-col>
      <el-col :span="12" class="flex-end">
        <el-button
          v-if="!permission['filling-team:driver-add']"
          icon="el-icon-plus"
          class="m-r-10"
          size="small"
          type="primary"
          plain
          @click="addNew"
          >新增司机</el-button
        >

        <el-upload
          v-if="!permission['filling-team:driver-upload']"
          :action="'/api/uic-system/fillteamuser/import/' + id"
          :limit="1"
          :show-file-list="false"
          :on-success="handleSuccess"
          :headers="headerObj"
          class="m-r-10"
        >
          <el-button icon="el-icon-upload" size="small" type="primary" plain
            >批量导入</el-button
          >
        </el-upload>
        <el-button
          v-if="!permission['filling-team:driver-download']"
          style="margin-left: -5px; font-size: 12px !important"
          icon="el-icon-download"
          size="small"
          type="text"
          @click="download"
          >下载司机信息模板
        </el-button>
      </el-col>
    </el-row>
    <el-table
      class="my-table m-t-10"
      :data="data"
      v-loading="loading"
      style="width: 100%"
      border
      :header-cell-style="{ background: '#eee', color: '#000' }"
    >
      <el-table-column type="index" align="center" label="序号" width="60" />
      <el-table-column prop="userName" label="司机姓名" min-width="100" />
      <el-table-column label="手机号" min-width="100">
        <template v-slot="scope">
          {{ scope.row.userPhone | defaultValue }}
        </template>
      </el-table-column>
      <el-table-column label="月额度使用上限（元）" min-width="150">
        <template v-slot="scope">
          {{ scope.row.creditMoney | defaultValue }}
        </template>
      </el-table-column>
      <el-table-column label="常用车辆" min-width="100">
        <template v-slot="scope">
          {{ scope.row.carNum | defaultValue }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="130">
        <template v-slot="scope">
          <el-dropdown @command="handleCommand">
            <div class="el-dropdown-link">
              操作列表
              <i class="el-icon-arrow-down el-icon--right"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                :command="{
                  c: 'view',
                  v: scope.row,
                }"
              >
                查看
              </el-dropdown-item>
              <el-dropdown-item
                :command="{
                  c: 'car',
                  v: scope.row,
                }"
              >
                常用车辆
              </el-dropdown-item>
              <el-dropdown-item
                :command="{
                  c: 'month-set',
                  v: scope.row,
                }"
              >
                月额度设置
              </el-dropdown-item>
              <el-dropdown-item
                :command="{
                  c: 'delete',
                  v: scope.row,
                }"
              >
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <app-pagination
      ref="paginationRef"
      :total="total"
      :page-size="page.size"
      class="m-t-20"
      @change="pageChange"
    />
    <el-dialog
      title="新增司机"
      append-to-body
      :visible.sync="showAddNewFlag"
      width="600px"
    >
      <el-form
        class="pa-12"
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="130px"
      >
        <el-form-item label="司机姓名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="userPhone">
          <el-input v-model="addForm.userPhone"></el-input>
        </el-form-item>
      </el-form>
      <div class="dividing-line m-t-20 m-b-20"></div>
      <div class="flex-end">
        <el-button
          type="primary"
          plain
          size="small"
          @click="showAddNewFlag = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          size="small"
          :loading="saveLoading"
          @click="confirmAdd"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="月额度设置"
      append-to-body
      :visible.sync="settingCardDialog"
      width="400px"
    >
      <el-form
        class="pa-12"
        :model="settingForm"
        ref="settingFormRef"
        label-width="130px"
      >
        <el-form-item label="月额度设置" prop="cardNo">
          <el-input v-model="settingForm.creditMoney"></el-input>
        </el-form-item>
      </el-form>
      <div class="dividing-line m-t-20 m-b-20"></div>
      <div class="flex-end">
        <el-button
          type="primary"
          plain
          size="small"
          @click="settingCardDialog = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          size="small"
          @click="confirmSettingcreditMoney"
          :loading="carLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="查看"
      append-to-body
      :visible.sync="showEditFlag"
      width="600px"
    >
      <el-form
        class="pa-12"
        :model="detailForm"
        :rules="addRules"
        ref="editFormRef"
        label-width="130px"
      >
        <el-form-item label="司机姓名" prop="name">
          <el-input v-model="detailForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="name">
          <el-input v-model="detailForm.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="车牌号码" prop="name">
          <select-filling-car-button
            class="f-g-1"
            :team-id="id"
            v-if="showEditFlag"
            size="large"
            :init-value="currRow"
            @change="detailCarChange"
          />
        </el-form-item>
        <el-form-item label="电子卡号" prop="name">
          <select-filling-electronic-card-button
            class="f-g-1"
            :team-id="id"
            v-if="showEditFlag"
            size="large"
            :init-value="currRow"
            @change="detailCardChange"
          />
        </el-form-item>
      </el-form>
      <div class="dividing-line m-t-20 m-b-20"></div>
      <div class="flex-end">
        <el-button
          type="primary"
          plain
          size="small"
          @click="showEditFlag = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          size="small"
          :loading="editLoading"
          @click="confirmEdit"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="常用车辆"
      append-to-body
      :visible.sync="showCarDialog"
      width="600px"
    >
      <el-form>
        <el-form-item label="车牌号" prop="cardNo">
          <el-tag
            v-for="(tag, index) in selectedCars"
            :key="tag.id"
            closable
            @close="removeSelectedcars(index)"
          >
            {{ tag.carNo }}
          </el-tag>
        </el-form-item>
      </el-form>
      <el-input
        style="width: 300px"
        size="small"
        placeholder="请输入车牌号"
        class="m-r-10"
        v-model="carsearch.keyword"
        @change="getCarData"
      />
      <el-table
        ref="multipleTable"
        @selection-change="handleSelectioncarChange"
        class="my-table m-t-10"
        :data="carData"
        v-loading="loading"
        style="width: 100%"
        border
        :header-cell-style="{ background: '#eee', color: '#000' }"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="index" align="center" label="序号" width="60" />
        <el-table-column prop="carNo" label="车牌号" min-width="100" />
      </el-table>
      <app-pagination
        ref="paginationRef"
        :total="cartotal"
        :page-size="carpage.size"
        class="m-t-20"
        @change="carpageChange"
      />
      <div class="dividing-line m-t-20 m-b-20"></div>
      <div class="flex-end">
        <el-button
          type="primary"
          plain
          size="small"
          @click="showCarDialog = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          size="small"
          @click="confirmCar"
          :loading="carLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import AppPagination from "@/components/business/app-pagination";
import {
  confirmWarning,
  downLoadFile,
  getRecords,
  getTotal,
  msgError,
  msgSuccess,
  strEquals,
} from "@/util/common-util";
import { getPage as getCarPage } from "@/api/business/filling-team-car";
import {
  bindCar,
  carByDrivers,
  getDrivers as getPage,
  monthlyLimitSettingByDriver,
  removeDriver as remove,
  saveDriver as save,
  update,
} from "@/api/business/filling-team-car-driver";
import SelectFillingElectronicCardButton from "@/components/business/select-filling-electronic-card-button";
import SelectFillingCarButton from "@/components/business/select-filling-car-button";
import { getToken } from "@/util/auth";
import { isMobile } from "@/util/validate";

export default {
  name: "contract-customer-detail-driver-tab",
  computed: {
    ...mapGetters(["permission"]),
  },
  components: {
    SelectFillingCarButton,
    SelectFillingElectronicCardButton,
    AppPagination,
  },
  props: ["id"],
  data() {
    return {
      headerObj: { "Uic-Auth": "bearer " + getToken() },
      loading: false,
      showAddNewFlag: false,
      showEditFlag: false,
      showBindVehicleFlag: false,
      showBindElectronicCardFlag: false,
      showSelectVehicleFlag: false,
      showSelectElectronicCardFlag: false,
      addForm: {
        userName: "",
        userPhone: "",
        teamId: "",
      },
      addRules: {
        userName: [
          { required: true, message: "请输入司机姓名", trigger: "blur" },
        ],
        userPhone: [
          { required: true, message: "请输入司机电话", trigger: "blur" },
        ],
      },
      saveLoading: false,
      removeLoading: false,
      editLoading: false,
      cardLoading: false,
      carLoading: false,
      data: [],
      search: {
        teamId: "",
        keyWord: "",
      },
      page: {
        size: 20,
        current: 1,
      },
      total: 0,
      currRow: {},
      settingForm: {},
      settingCardDialog: false,
      detailForm: {},
      showCarDialog: false,
      carData: [],
      cartotal: 0,
      carloading: false,
      carpage: {
        size: 20,
        current: 1,
      },
      selectedCars: [],
      carsearch: {
        teamId: "",
        keyword: "",
      },
    };
  },
  created() {
    this.search.teamId = this.id;
    this.query();
  },
  methods: {
    getCarbyDriverList() {
      carByDrivers({ current: 1, size: 20, teamUserId: this.currRow.id }).then(
        (res) => {
          this.selectedCars = getRecords(res);
          // if (this.selectedCars.length) {
          //   console.log(this.selectedCars);
          //   this.selectedCars.forEach((row) => {
          //     this.$refs.multipleTable.toggleRowSelection(row);
          //   });
          // } else {
          //   this.$refs.multipleTable.clearSelection();
          // }
        }
      );
    },
    //移除已选中的车辆
    removeSelectedcars(index) {
      console.log(index);
      this.selectedCars.splice(index, 1);
      console.log(this.selectedCars);
      if (this.selectedCars.length) {
        this.selectedCars.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选择常用车辆进行绑定
    handleSelectioncarChange(val) {
      this.selectedCars = val;
      console.log(val);
    },
    carpageChange(_page) {
      this.carpage = _page;
      this.getCarData();
    },
    //获取车牌号列表
    getCarData() {
      this.carloading = true;
      this.carsearch.teamId = this.id;
      getCarPage(this.carpage, this.carsearch)
        .then((res) => {
          console.log(res.data.data);
          console.log(getRecords(res));
          this.carData = getRecords(res);
          this.cartotal = getTotal(res);
          this.carloading = false;
        })
        .then(() => {
          this.carloading = false;
        });
    },
    //设置月额度
    confirmSettingcreditMoney() {
      this.settingForm.teamId = this.id;
      this.$refs.settingFormRef.validate((valid, errObj) => {
        if (valid) {
          this.saveLoading = true;
          monthlyLimitSettingByDriver(this.settingForm)
            .then((res) => {
              msgSuccess();
              this.query();
              this.settingCardDialog = false;
              this.saveLoading = false;
            })
            .catch(() => {
              this.saveLoading = false;
            });
        }
      });
    },
    handleCommand(_command) {
      const row = _command.v;
      if (strEquals(_command.c, "view-addcard")) {
        this.showAddNewFlag = true;
        this.addForm = row;
        this.type = "view";
      }
      if (strEquals(_command.c, "car")) {
        this.currRow = row;
        this.showCarDialog = true;
        this.getCarbyDriverList();
        this.getCarData();
      }
      if (strEquals(_command.c, "delete")) {
        confirmWarning("司机信息", `确定删除司机 ${row.userName}？`, () => {
          this.removeLoading = true;
          remove(row.id)
            .then((res) => {
              this.removeLoading = false;
              this.query();
              msgSuccess();
            })
            .catch(() => {
              this.removeLoading = false;
            });
        });
      }
      if (strEquals(_command.c, "month-set")) {
        this.settingForm = row;
        this.settingCardDialog = true;
      }
    },
    handleSuccess() {
      msgSuccess("上传成功");
    },
    query() {
      this.loading = true;
      getPage(this.page, this.search)
        .then((res) => {
          this.data = getRecords(res);
          this.total = getTotal(res);
          this.loading = false;
        })
        .then(() => {
          this.loading = false;
        });
    },
    addNew() {
      this.showAddNewFlag = true;
    },
    confirmAdd() {
      if (!isMobile(this.addForm.userPhone))
        return msgError("手机号码格式不正确");

      this.addForm.teamId = this.id;
      this.$refs.addFormRef.validate((valid, errObj) => {
        if (valid) {
          this.saveLoading = true;
          save(this.addForm)
            .then((res) => {
              msgSuccess();
              this.query();
              this.showAddNewFlag = false;
              this.saveLoading = false;
            })
            .catch(() => {
              this.saveLoading = false;
            });
        }
      });
    },
    pageChange(_page) {
      this.page = _page;
      this.query();
    },
    detailCardChange(_card) {
      this.detailForm.cardNo = _card.cardNo;
      this.detailForm.cardId = _card.cardId;
    },
    detailCarChange(_car) {
      this.detailForm.carNo = _car.carNo;
      this.detailForm.carId = _car.carId;
    },
    confirmCar() {
      let params = {
        teamUserId: this.currRow.id,
        teamId: this.id,
        bindCarIds: this.selectedCars.map((item) => item.id),
      };
      this.carLoading = true;
      bindCar(params)
        .then((res) => {
          msgSuccess();
          this.showCarDialog = false;
          this.query();
          this.carLoading = false;
        })
        .catch(() => {
          this.carLoading = false;
        });
    },
    confirmEdit() {
      if (!isMobile(this.detailForm.userPhone))
        return msgError("手机号码格式不正确");

      this.detailForm.teamId = this.id;
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          this.editLoading = true;
          update(this.detailForm)
            .then((res) => {
              msgSuccess();
              this.query();
              this.showEditFlag = false;
              this.editLoading = false;
            })
            .catch(() => {
              this.editLoading = false;
            });
        }
      });
    },
    async download() {
      await downLoadFile(
        "/api/uic-system/fillteamuser/export-template",
        "司机信息模板.xls"
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.my-table {
  ::v-deep .el-button--small {
    padding: 0 5px !important;
    font-size: 14px !important;
  }

  ::v-deep td {
    padding: 8px 0 !important;
  }
}
</style>
